import { View, Image, Text } from "@tarojs/components";
import React from "react";
import { HideLoading, ShowLoading, ShowToast, ToPage } from "@/utils";
import { articleType } from "@/types";
import ImgList from "@/components/imgList";
import http from "@/request";
import Taro from "@tarojs/taro";

import "./index.scss"

const ArticleItem: React.FC<{ article: articleType, edit?: boolean, onChange: () => void }> = ({ article, edit, onChange }) => {

    const toDetail = (article) => {
        ToPage(`/pages/article/detail/index?id=${article.id}`)
    }

    const editItem = (e) => {
        e.stopPropagation()
        ToPage(`/pages/article/detail/index?id=${article.id}&mode=edit`)
    }
    const deleteItem = (e) => {
        e.stopPropagation()
        Taro.showModal({
            title: '是否删除所选笔记？',
            content: '',
            success: (res: any) => {
                if (res.confirm) {
                    ShowLoading('删除中')
                    http.delete(`/article/delete/${article.id}`).then(_ => {
                        onChange()
                        HideLoading()
                    }).catch(err => {
                        ShowToast(err.msg || '删除失败')
                    })
                }
            }
        })
    }

    return <View className="article-item-container font-size28 flex-column" onClick={() => toDetail(article)}>
        <View className="info-title font-size32">{article.title}</View>
        <View className="user-info flex-row flex-item">
            <Image className="user-avator" src={article.avatarUrl || ''}></Image>
            <View className="user-name flex1">{article.userName || ''}</View>
            {
                edit ? <>
                    <Text onClick={editItem} className="edit-btn font-size40 iconfont icon-bianji"></Text>
                    <Text onClick={deleteItem} className="edit-btn font-size40 iconfont icon-base-del"></Text>
                </> : null
            }
        </View>
        <View className="info-body font-size28">
            <ImgList imgList={(article.imgs || []).slice(0, 4)}></ImgList>
            <View className="content-text">
                {article.content}
            </View>
        </View>
        <View className="info-data font-size28 flex-row">
            <View className="val">{article.likeNum || 0}赞同</View>
            <View className="val">{article.commentNum || 0}评论</View>
        </View>
    </View>
}

export default ArticleItem